package com.lt.flashcard.model.service;

import java.io.Serializable;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.zkoss.zkplus.hibernate.HibernateUtil;

/**
 * Basic DAO provides functions to work with entity
 * @author ocsen
 * @version 1.0
 * @created 15-Aug-2012 21:38:20
 */
public class BasicDAO<T extends Serializable> {
	
	protected final Class<T> type;
	
	public BasicDAO(Class<T> type) {
		this.type = type;
	}

	protected Session getCurrentSession() {
		return HibernateUtil.currentSession();
	}
	
	/**
	 * Save or update entity to database
	 * @param entity
	 * @return
	 * @throws Exception 
	 */
	public boolean save(T entity) {
		getCurrentSession().saveOrUpdate(entity);
		return true;
	}
	
	/**
	 * Delete entity from database
	 * @param entity
	 */
	public void delete(T entity) {
		getCurrentSession().delete(entity);
	}
	
	public T findByID(Serializable key) {
		return (T) getCurrentSession().get(type , key);
	}
	
	public Criteria createCriteria() {
		return getCurrentSession().createCriteria(type);
	}
}
